<template>
  <div class="app-container">
    <el-card class="box-card" shadow="always" v-show="showSearch">
      <el-form :model="queryParams" ref="queryForm" :inline="true" label-width="90px" @submit.native.prevent>
        <el-form-item label="客户名称" prop="supplierId">
          <el-select
            v-model="queryParams.supplierId"
            filterable
            clearable
            remote
            reserve-keyword
            placeholder="请选择客户"
            :remote-method="(query) => remoteMethod(query, 'supplier', 'supplierName')"
            :loading="loading"
            @change="handleQuery"
          >
            <el-option v-for="item in supplierOptions" :key="item.id" :label="item.supplierName" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="经手人" prop="userId">
          <el-select
            v-model="queryParams.userId"
            filterable
            clearable
            remote
            reserve-keyword
            placeholder="请选择经手人"
            :loading="loading"
            @change="handleQuery"
          >
            <el-option v-for="item in userList" :key="item.userId" :label="item.realityName" :value="item.userId" />
          </el-select>
        </el-form-item>
        <el-form-item label="客户区域">
          <el-select v-model="queryParams.areaId" placeholder="请选择客户区域" @change="handleQuery">
            <el-option v-for="item in areaList" :key="item.id" :value="item.id" :label="item.areaName"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="归属部门" prop="deptId">
          <el-tree-select
            v-model="queryParams.deptId"
            :data="deptOptions"
            :props="{ value: 'id', label: 'label', children: 'children' }"
            value-key="id"
            placeholder="请选择归属部门"
            check-strictly
            @change="handleDeptChange"
          />
        </el-form-item>
        <el-form-item label="产品分类" prop="classifyId">
          <el-tree-select
            :props="{ value: 'id', label: 'classifyName', children: 'children' }"
            v-model="queryParams.classifyId"
            :data="categoryList"
            clearable
            :render-after-expand="false"
          />
        </el-form-item>

        <el-form-item label="产品名称" prop="goodsName">
          <el-input v-model="queryParams.goodsName" placeholder="请输入产品名称" clearable @keyup.enter="handleQuery" />
        </el-form-item>
        <!-- <el-form-item label="即将到期" prop="endTime">
          <el-select v-model="queryParams.status" placeholder="请选择到期时间" clearable>
            <el-option v-for="item in renewal_time_type" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item> -->

        <el-form-item label="跟单阶段" prop="followStageId">
          <el-select v-model="queryParams.followStageId" placeholder="请选择跟单阶段" clearable @change="handleQuery">
            <!-- <el-option v-for="item in followStage" :key="item.id" :label="item.name" :value="item.id" /> -->
            <el-option-group v-for="(group, index) in followStage" :key="index" :label="group.followTypeName">
              <el-option v-for="item in group.jzgFollowStageVoList" :key="item.id" :label="item.name" :value="item.id" />
            </el-option-group>
          </el-select>
        </el-form-item>

        <el-form-item label="开始时间" prop="beginDate">
          <el-date-picker
            v-model="dateRange"
            format="YYYY-MM-DD"
            :value-format="YYYY - MM - DD"
            type="daterange"
            align="right"
            unlink-panels
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="到期时间" prop="endDate">
          <el-date-picker
            v-model="endDateRange"
            format="YYYY-MM-DD"
            :value-format="YYYY - MM - DD"
            type="daterange"
            align="right"
            unlink-panels
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            @change="endDateChange"
          >
          </el-date-picker>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="handleQuery">搜索</el-button>
          <el-button @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <el-card class="box-card" shadow="always" :body-style="{ padding: '20px' }">
      <template #header>
        <div>
          <el-row :gutter="10" class="mb8">
            <el-radio-group is-button class="ml10" @change="changeRadio" v-model="radio">
              <el-radio-button value="">全部单据</el-radio-button>
              <el-radio-button value="audit">我的审核</el-radio-button>
              <el-radio-button v-for="item in renewal_time_type" :key="item.value" :label="item.value">
                {{ item.label }}
              </el-radio-button>
            </el-radio-group>
            <right-toolbar :v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
          </el-row>
        </div>
      </template>
      <el-table
        border
        show-summary
        :summary-method="getSummaries"
        v-loading="loading"
        :data="dataSource"
        @selection-change="handleSelectionChange"
        :row-style="payRowStyle"
      >
        <el-table-column type="selection" width="75" align="center" :selectable="selectHandle" fixed="left" />
        <el-table-column label="#" type="index" width="35" fixed="left"> </el-table-column>
        <el-table-column label="单据编号" align="center" width="200" fixed="left">
          <template #default="scope">
            <el-button type="text" @click="handleView(scope.row)">{{ scope.row.payOrderCode }}</el-button>
          </template>
        </el-table-column>
        <el-table-column label="客户分类" align="center" prop="supplierClassifyName" />
        <el-table-column label="客户名称" align="center" prop="supplierName" />
        <el-table-column label="销售区域" align="center" prop="saleAreaName" />
        <el-table-column label="联系人" align="center" prop="contacts" />
        <el-table-column label="产品名称" align="center" prop="goodsName" />
        <!-- <el-table-column label="规格" align="center" prop="goodsSpec" /> -->
        <el-table-column label="续费金额" align="center" prop="payAmount" />
        <el-table-column label="开始时间" align="center" prop="beginDate" width="105" sortable />
        <el-table-column label="周期" align="center" prop="periodicNum" />
        <el-table-column label="到期时间" align="center" prop="endDate" width="105" sortable />
        <el-table-column label="剩余天数" align="center" prop="remainingDays" width="105" />
        <el-table-column label="客户经理" align="center" prop="operationManagerName" />
        <!-- <el-table-column label="经手人" align="center" prop="userName" /> -->
        <el-table-column label="跟单阶段" align="center" prop="stageName" width="90">
          <template #default="scope">
            <el-button type="text" @click="handleDetail(scope.row)">{{ scope.row.name || '未进行' }}</el-button>
          </template>
        </el-table-column>
        <el-table-column label="备注" align="center" prop="comment" />
        <el-table-column label="操作" align="center" prop="orderStatus" width="150" fixed="right">
          <template #default="scope">
            <el-button type="text" @click="handleStatus(scope.row)" v-hasPermi="['order:followOrder:add']" v-show="scope.row.stageName != '3'"
              >续费跟单</el-button
            >
            <el-button type="text" @click="handleDetail(scope.row)" v-show="scope.row.stageName === '3'">查看</el-button>
            <!-- <el-button type="text" @click="followOrderDelete(scope.row)"
              v-hasPermi="['order:followOrder:remove']">删除跟单</el-button> -->
          </template>
        </el-table-column>
      </el-table>
      <pagination
        v-show="total > 0"
        :total="total"
        v-model:page.sync="queryParams.pageNum"
        v-model:limit.sync="queryParams.pageSize"
        @pagination="getList"
      />
    </el-card>
    <statusForm ref="statusForm" @ok="getList"></statusForm>
    <trackingDetail ref="trackingDetail"></trackingDetail>
  </div>
</template>

<script>
import statusForm from './modules/statusForm.vue';
import trackingDetail from './modules/trackingDetail.vue';
import api from '@/api/system/user';
import listMixin from '@/mixins/listMixin';
import useExport from '@/components/PPTist/hooks/useExport';
import { randomUUID } from '@/utils/util';
import { allListByType } from '@/api/goods/followStage';
import { formatDate } from '@/utils/index';
import request from '@/utils/request';
import moment from 'moment';
export default {
  name: 'quotationTracking',
  dicts: ['inventory_status', 'counting_method'],
  mixins: [listMixin],
  components: { statusForm, trackingDetail },
  data() {
    return {
      showSearch: true, // Whether to show the search form
      queryParams: {
        // Query parameters for the table
        pageNum: 1, // Current page number
        pageSize: 10, // Number of records per page
        deptId: ''
      },
      dateRange: [], // Date range for the created time
      radio: '',
      endDateRange: [],
      loading: false, // Loading state of the table
      dataSource: [], // Data for the table
      total: 0, // Total number of records
      multiple: false, // Whether multiple rows are selected
      categoryList: [], //产品分类
      deptOptions: [], //归属部门
      selectedSaleOptions: [],
      renewal_time_type: [], //到期时间
      followStage: [], //跟单状态
      currentRow: {}, // Current row data
      supplierOptions: [], //客户
      urls: {
        list: '/order/payOrderDetail/list',
        auditList: '/order/payOrderDetail/myAuditList',
        delete: '/order/payOrderDetail'
      },
      auditStatus: ''
    };
  },
  mounted() {
    if (this.$route.query.payOrderId) {
      this.queryParams.payOrderId = this.$route.query.payOrderId;
      setTimeout(() => {
        this.getList();
      }, 300);
    } else {
      this.queryParams = {
        pageNum: 1,
        pageSize: 10
      };
    }
    this.getDicts(['renewal_status', 'renewal_time_type']);
    this.getTreeSelect(); // 初始化部门数据
    this.listSysUser();
    this.getArea();
    allListByType().then((res) => {
      this.followStage = res || [];
    });
    this.getCategoryAllList();
    this.getSupplierAllList(1);
  },
  methods: {
    getQueryParams() {
      let params = Object.assign({}, this.queryParams);
      params.params = { ...this.queryParams };
      params.params['auditStatus'] = this.auditStatus;
      console.log('this.params :>> ', params);
      if (this.dateRange && this.dateRange.length) {
        params.params['beginCreateTime'] = moment(this.dateRange[0]).format('YYYY-MM-DD 00:00:00');
        params.params['endCreateTime'] = moment(this.dateRange[1]).format('YYYY-MM-DD 23:59:59');
      }
      if (this.endDateRange && this.endDateRange.length) {
        params.params['endDateBegin'] = moment(this.endDateRange[0]).format('YYYY-MM-DD 00:00:00');
        params.params['endDateEnd'] = moment(this.endDateRange[1]).format('YYYY-MM-DD 23:59:59');
      }
      return params;
    },
    remoteMethod(query, listKey, key) {
      const optionKey = listKey + 'Options';
      if (query !== '') {
        this[optionKey] = this[listKey + 'List'].filter((item) => {
          return item[key].toLowerCase().indexOf(query.toLowerCase()) > -1;
        });
      } else {
        this[optionKey] = this[listKey + 'List'];
      }
    },
    async handleDeptChange(value) {
      const response = await optionselect(value.detail.value.slice(-1)[0].value);
      this.postOptions = JSON.parse(
        JSON.stringify(response.data)
          .replace(/postName/g, 'text')
          .replace(/deptId/g, 'value')
      );
      console.log('postOptions :>> ', this.postOptions);
      this.form.postIds = [];
    },

    handleStatus(row) {
      this.$refs.statusForm.edit(row);
    },
    handleDetail(row) {
      this.$refs.trackingDetail.detail(row);
    },
    /** 查询部门下拉树结构 */
    async getTreeSelect() {
      const res = await api.deptTreeSelect();
      this.deptOptions = res.data;
    },
    handleView(row) {
      this.$router.push({ name: 'PayOrderAdd', query: { id: row.payOrderId, enterType: '1' } });
    },
    payRowStyle({ row, column, rowIndex, columnIndex }) {
      if (row.stageName === '3') {
        return {
          backgroundColor: '#e1ffeb'
        };
      }
    },
    changeRadio() {
      let end = new Date().getTime();
      let start = new Date().getTime();
      switch (this.radio) {
        case '':
          this.endDateRange = [];
          this.auditStatus = '';
          break;
        case 'audit':
          this.endDateRange = [];
          this.auditStatus = 0;
          break;
        case '0':
          this.auditStatus = '';
          end += 3600 * 1000 * 24 * 7;
          this.endDateRange = [formatDate(start).substring(0, 10), formatDate(end).substring(0, 10)];
          break;
        case '1':
          this.auditStatus = '';
          end += 3600 * 1000 * 24 * 30;
          this.endDateRange = [formatDate(start).substring(0, 10), formatDate(end).substring(0, 10)];
          break;
        case '2':
          this.auditStatus = '';
          end += 3600 * 1000 * 24 * 90;
          this.endDateRange = [formatDate(start).substring(0, 10), formatDate(end).substring(0, 10)];
          break;
      }
      this.handleQuery();
    },
    endDateChange() {
      this.radio = '';
    },
    getSummaries(param) {
      const { columns, data } = param;
      const sums = [];
      columns.forEach((column, index) => {
        if (index === 0) {
          //只找第一列放合计
          sums[index] = '合计：';
          return;
        }
        const values = data.map((item) => Number(item[column.property])); //把对应一列中的之全部取出，放到一个数组中
        const keyArr = ['payAmount'];
        if (keyArr.includes(column.property)) {
          sums[index] = values.reduce((prev, curr) => {
            const value = Number(curr);
            if (!Number.isNaN(value)) {
              return prev + curr;
            } else {
              return prev;
            }
          }, 0);
        } else {
          sums[index] = '-';
        }
      });
      return sums;
    },
    resetQuery() {
      this.dateRange = [];
      this.endDateRange = [];
      this.auditStatus = '';
      this.radio = '';
      (this.queryParams = {
        //查询条件
        pageNum: 1,
        pageSize: 10
      }),
        this.getList();
    },
    getList() {
      this.loading = true;
      var params = {
        url: this.auditStatus === 0 ? this.urls.auditList : this.urls.list,
        method: 'get',
        params: this.getQueryParams() //查询条件
      };
      console.log('params :>> ', params);
      request(params).then((res) => {
        this.loading = false;
        if (res.code == 200) {
          this.dataSource = res.rows;
          this.total = res.total;
          if (typeof this.listAfter === 'function') {
            this.listAfter();
          }
        } else {
          this.$modal.msgError(res.msg);
        }
      });
    },
    followOrderDelete(row) {
      console.log('row :>> ', row);
      this.$modal
        .confirm('确定删除？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        .then(() => {
          request({
            url: '/order/followOrder' + '/' + row.followOrderIdList,
            method: 'delete'
          }).then((res) => {
            if (res.code == 200) {
              this.$modal.msgSuccess('删除成功');
              this.selectOk();
            } else {
              this.$modal.msgError(res.msg);
            }
          });
        })
        .catch(() => {});
    }
  }
};
</script>
<style type="text/css" scoped>
.box-card {
  margin-bottom: 10px;
}
</style>
